#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File  :get_jd_price.py
# Time  :2025/3/28 9:10
# Email :fortunatedong@163.com
# Author:by Adonli
import base64
import datetime
import json
import re
import time

import cv2
import numpy as np
import pandas as pd
import toml
from playwright.sync_api import sync_playwright
from dingtalk.guotie_jd_price_messages_push import MessagePush

from utils.guotie_jd_price.jingdong_cookie import JingDongLogin

class GetJDPrice(object):
    def __init__(self,pw):
        self.cfg = toml.load('../../settings/configs.toml')
        self.datas_path = self.cfg['PATH']['DatasPath']
        self.pw = pw
        browser = pw.chromium.launch(headless=True, channel="chrome")
        context = browser.new_context(
            user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
        # with open('auth/jingdong_cookies.json', 'r') as f:
        #     cookies = json.load(f)
        # print(cookies)
        # context.add_cookies(cookies)
        with open('auth/guotie_jd_ziuser_jingdong_cookies.json', 'r') as f:
            cookies = json.load(f)
        # print(cookies)
        context.add_cookies(cookies)
        self.page = context.new_page()
        self.page.set_extra_http_headers({
            "Accept-Language": "en-US,en;q=0.9",
            "Referer": "https://www.jd.com/"
        })
        with open('auth/stealth.min.js', 'r') as f:
            js = f.read()
        self.page.add_init_script(js)
        # print(self.datas_path)
    def read_sku_url(self):
        df = pd.read_csv(f"../../{self.datas_path}",dtype=str)
        df = df[df["SKU编号"].isna() == False]
        # print(df)
        return df

    def text_replace(self,html_text):
        return html_text.replace("	", "").replace("\r", "").replace("\n", "").replace("\\", "").replace("\t", "")

    def track(self):

        verify_bg_src = self.page.locator("//img[@id='cpc_img']").get_attribute("src")
        # print(bg_src)
        image_base64 = verify_bg_src[22:]
        imgdata = base64.b64decode(image_base64)
        # print(imgdata)
        # 下载图片
        with open(f"img/verify_bg_src.png", 'wb') as f:
            f.write(imgdata)

        verify_small_src = self.page.locator("//img[@id='small_img']").get_attribute("src")
        image_base64 = verify_small_src[22:]
        imgdata = base64.b64decode(image_base64)
        # print(imgdata)
        # 下载图片
        with open(f"img/verify_small_src.png", 'wb') as f:
            f.write(imgdata)

        bg_path = 'img/verify_bg_src.png'  # 背景图片路径
        slider_path = 'img/verify_small_src.png'  # 滑块图片路径
        verify_bg_img = cv2.imread(bg_path)
        verify_tp_img = cv2.imread(slider_path)  # 读取到两个图片，进行灰值化处理
        bg_gray = cv2.cvtColor(verify_bg_img, cv2.COLOR_BGR2GRAY)

        bg_gray = cv2.GaussianBlur(bg_gray, (5, 5), 0)

        bg_edge = cv2.Canny(bg_gray, 30, 100)

        rgb_bg_gray = cv2.cvtColor(bg_edge, cv2.COLOR_GRAY2RGB)

        sd_gray = cv2.cvtColor(verify_tp_img, cv2.COLOR_BGR2GRAY)
        sd_gray = cv2.GaussianBlur(sd_gray, (5, 5), 0)
        sd_edge = cv2.Canny(sd_gray, 30, 100)
        rgb_sd_gray = cv2.cvtColor(sd_edge, cv2.COLOR_GRAY2RGB)
        result = cv2.matchTemplate(rgb_bg_gray, rgb_sd_gray, cv2.TM_CCORR_NORMED)
        _, _, _, max_loc = cv2.minMaxLoc(result)
        cv2.rectangle(verify_bg_img, (max_loc[0], max_loc[1]), (max_loc[0] + 50, max_loc[1] + 50),
                      (0, 255, 0), 2)

        cv2.imwrite("img/verify_bg_img.png", verify_bg_img)

        distance = max_loc[0] + 8
        def get_track(distance):
            # 移动轨迹
            track = []
            # 当前位移
            current = 0
            # 减速阈值
            mid = distance * 4 / 5
            # 计算间隔
            t = 0.3
            # 初速度
            v = 2
            # track.append(0)
            while current < distance:
                if current < mid:
                    # 加速度为2
                    a = 4
                else:
                    # 加速度为-2
                    a = -3
                v0 = v
                # 当前速度
                v = v0 + a * t
                # 移动距离
                move = v0 * t + 1 / 2 * a * t * t
                # 当前位移
                current += move
                track.append(round(move))
            return track

        tracks = get_track(distance)
        return tracks

    def verify(self):
        count = 0
        while count < 10:
            self.page.locator("//div[@class='verifyBtn']").click()
            dropbutton = self.page.locator("//img[@class='move-img']")
            box = dropbutton.bounding_box()
            print(box)
            self.page.mouse.move(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2)
            self.page.mouse.down()
            x = box["x"] + box["width"] / 2
            # 这个把缺口获取到的长度放到轨迹加工一下得到一个轨迹
            tracks = self.track()
            for track in tracks:
                # 循环鼠标按照轨迹移动
                # steps 是控制单次移动速度的比例是1/10 默认是1 相当于 传入的这个距离不管多远0.1秒钟移动完 越大越慢
                self.page.mouse.move(x + track, 0)
                x += track
            # 移动结束鼠标抬起
            self.page.mouse.up()
            if not self.page.query_selector("//div[@class='verifyBtn']"):
                print("京东快速验证成功")
                update_verify_data = {"code": 0,
                                      "status": "success",
                                      "result": "京东快速验证成功",
                                      "update": "京东快速验证成功,正在重启"}
                return update_verify_data

            else:
                print("京东快速验证失败")
                # print(self.page.locator("//*[@class='JDJRV-bigimg']/img").get_attribute("src"))
                self.page.reload()
                count += 1
                if count == 10:
                    update_verify_data = {"code": 4,
                                          "status": "failed",
                                          "result": "京东快速验证失败",
                                          "update": "京东快速验证失败，需管理员处理后重启！"}
                    return update_verify_data
    def get_price(self,sku,sku_name,guotie_price,jd_url):
        self.page.goto(jd_url)
        time.sleep(3)
        a = self.page.locator("//div[@class='verifyBtn']").count()
        if a != 0:
            update_verify_data = self.verify()
            if update_verify_data["code"] == 4:
                print("滑块验证10次错误！！！！！！！！！！！！！")
                return update_verify_data

        code = self.page.content()
        code_result = self.text_replace(code)
        # print(code)
        time.sleep(1)
        sku_title_re = re.compile(r'<div class="sku-name">.*?id="bgIcon".*?>(.*?)</div>', re.S)
        sku_title_result = re.findall(sku_title_re, code_result)[0].strip()
        # logs.info(sku_title_result)
        if "商品已下柜" in code:
            sku_price = {
                "guotie_sku": sku,
                "sku_name": sku_name,
                "guotie_price": "{:.2f}".format(float(guotie_price)),
                "jd_url": jd_url,
                "jingdong_sell_price": "0.00",
                "remark":"该商品京东链接已下柜，请及时更换京东比价链接"
            }
            print(f"{datetime.datetime.now()}--国铁商城{sku}京东价格:该商品京东链接已下柜，请及时更换链接")
            return sku_price
        if "finalPrice" in code:
            sku_price_re = re.compile(r'<span class="finalPrice".*?<span class="price">(.*?)</span>', re.S)
            sku_price_result = re.findall(sku_price_re, code_result)[0].strip()
            print(f"{datetime.datetime.now()}--国铁商城{sku}京东价格:{sku_price_result}")
        else:
            sku_price_re = re.compile(r'<span class="p-price.*?">.*?class="price.*?">(.*?)</span>', re.S)
            sku_price_result = re.findall(sku_price_re, code_result)[0].strip()
            print(f"{datetime.datetime.now()}--国铁商城{sku}京东价格:{sku_price_result}")
        sku_price = {
            "guotie_sku": sku,
            "sku_name": sku_name,
            "guotie_price": "{:.2f}".format(float(guotie_price)),
            "jd_url": jd_url,
            "jingdong_sell_price": "{:.2f}".format(float(sku_price_result)),
            "remark": ""
        }
        # print(sku_price)
        return sku_price
    def get_jingdong_price_main(self):
        df = self.read_sku_url()
        # print(df)
        if df.empty:
            sku_price = {
                "guotie_sku": "",
                "sku_name": "",
                "guotie_price": "",
                "jd_url": "",
                "jingdong_sell_price": "",
                "remark": "",
                "contrast":""
            }
            df_price = pd.DataFrame([sku_price])
            df_price.to_csv("../../Datas/jingdong_sell_price.csv", index=False)
            return df_price
        else:
            result_price = []
            for index, row in df.iterrows():
                # print(row["SKU编号"])
                sku_price = self.get_price(row["SKU编号"], row["商品名称"], row["国铁价格"], row["京东URL"])
                # print(sku_price)
                result_price.append(sku_price)
            df_price = pd.DataFrame(result_price)
            diff = pd.to_numeric(df_price["jingdong_sell_price"], errors="coerce") - pd.to_numeric(df_price["guotie_price"],
                                                                                             errors="coerce")
            df_price["contrast"] = np.where(diff > 0, "正常", "异常")
            df_price.to_csv("../../Datas/jingdong_sell_price.csv", index=False)
            # print(result_price)
            return result_price,df_price

def Job():
    try:
        max_retries = 10
        retries = 0
        while retries < max_retries:
            with sync_playwright() as pw:
                try:
                    gjd = GetJDPrice(pw)
                    result_price,df_price = gjd.get_jingdong_price_main()
                    MessagePush(result_price).success_text_push()
                    # print(a)
                except Exception as e:
                    print(e)
                    JingDongLogin(pw,"xxxxxxxxxxxxxx","xxxxxxxxxxx","guotie_jd_ziuser").save_jingdong_cookie()
                    retries += 1
                else:
                    break
    except Exception as e:
        print(f"任务执行异常: {str(e)}")

# if __name__ == '__main__':
#     with sync_playwright() as pw:
#         gjd = GetJDPrice(pw)
#         result_price, df_price = gjd.get_jingdong_price_main()
#         MessagePush(result_price).success_text_push()
